function iniUploadFile(id,upload_url, mime_types){
    if(mime_types == undefined){
        mime_types = [{title : "Image files", extensions : "mp4,flv,doc,docx,ppt,pptx,pdf,xls,xlsx"}];
    }

    if(!$("#" + id + "_uploader").length){
        var box = $("<div>").attr("id", id + "_uploader");
        $("#" + id + "_uploader_container").append(box);
    }

    $("#" + id + "_uploader").pluploadQueue({
        // General settings
        runtimes : "html4",
        url : upload_url,
        unique_names : true,
        multi_selection : true,
        filters : {
            mime_types: mime_types,
            max_file_size: '400mb'
        }
    });
}

// function my_plupload_delete(id) {
//     $('#' + id).on('click', '#old_file.plupload_delete a', function(e) {
//         var $this = $(this).parents("div[id$='_uploader']");
//         var _this = $(this).parents("li#old_file");
//         var name = _this.attr("filename");
//
//         layer.confirm('您确认想要删除附件吗？', {
//             icon: 3,  skin: 'layer-ext-moon'
//         }, function(index){
//             for(var i=0; i<plupload_data_array.length; i++){
//                 var obj = plupload_data_array[i];
//                 if(obj.name == name){
//                     plupload_data_array.splice(i,1);
//                     _this.remove();
//                     layer.close(index);
//                     return;
// 				}
//             }
//         });
//
//     });
// }

function init_plupload_data(id){
    var html = "";
    if(plupload_data_array.length < 1){
        return html;
    }

    for(var i=0; i<plupload_data_array.length; i++){
        var obj = plupload_data_array[i];
        html += '<li id="old_file" fileName="' + obj.name + '" class="plupload_delete">' +
            '<div class="plupload_file_name"><span>' + obj.name + '</span></div>' +
            '<div class="plupload_file_action"><a href="#" style="display: block;"></a></div>' +
            '<div class="plupload_file_status">100%</div>' +
            '<div class="plupload_file_size">' + plupload.formatSize(obj.size) + '</div>' +
            '<div class="plupload_clearer">&nbsp;</div>' +
            '</li>';
    }
    return html;
}

var plupload_data_array = new Array();
function add_plupload_data(id, files){
    plupload_data_array = new Array();

    for(var i=0; i<files.length; i++){
        plupload_data_array.push(files[i]);
        // remove_upload_data_array(files[i].name);
    }
}

function my_plupload_cancel(index, id){
    var status = $("#" + id + "_uploader").parents("div[id^=layui-layer]").attr("upload_status");
    if(status == 'true' || status == true){
        return true;
    }
    layer.confirm('<div style="text-align:center;line-height:60px;">文件未上传完，关闭会在后台继续上传</div>', {
        btn: ['确定','取消'] //按钮
    }, function(i){
//		var maxmin = $("#" + id + "_uploader").parents("div[id^=layui-layer]").find(".layui-layer-maxmin").length;
//		if(maxmin < 1){
//			$("#" + id + "_uploader").parents("div[id^=layui-layer]").find(".layui-layer-min").trigger("click");
//		}
        $("#" + id + "_uploader").parents("div[id^=layui-layer]").remove();
        layer.close(i);
    });
    return false;
}

//开始上传
function my_plupload_start(id){
//	console.log("开始上传！");
//	$("#" + id).parents("div[id^=layui-layer]").find(".layui-layer-min").trigger("click");
    $("#" + id).parents("div[id^=layui-layer]").attr("upload_status", "false");
}

//上传成功
function my_plupload_success(id){
//	console.log("上传成功！");
    $("#" + id).parents("div[id^=layui-layer]").attr("upload_status", "true");
}

var file_id_path = {};
function backUpCallBack(id, response_, fileId) {
    var data = eval("(" + response_ + ")");
    var result = data['result'];
    var value = $("#fileList").val();
    var upload = result.fileId + ";" + result.fileName;
    value += value == '' ? upload : "," + upload;
    $("#fileList").val(value)

    file_id_path[fileId] = upload;
}

// function remove_upload_data_array(name) {
// 	var array = plupload_upload_data_array;
//     plupload_upload_data_array = new Array();
//     for(var i=0; i<array.length; i++){
//         if(array[i].name == name){
//             plupload_upload_data_array.push(array[i]);
//         }
//     }
// }

//id 按钮id
function delCallback(id, rm_files){
    console.log(rm_files.id);
    var result = '';
    for(var i=0; i<plupload_data_array.length; i++){
        var upload = file_id_path[plupload_data_array[i].id];
        result += result == '' ? upload : "," + upload;
    }
    $("#fileList").val(result)
}



/***
 * 新版上传控件
 * @param id
 * @param upload_url
 * @param mime_types
 */

// 上传ip
var storageId = "";
// key
var fastUser = "";
// 秘钥
var fastUserkey = "";
function initUploadFile(id,upload_url, mime_types,file_size,storage_id,fast_user,fast_user_key){
    storageId = storage_id;
    fastUser = fast_user;
    fastUserkey = fast_user_key;
    if(undefined == mime_types  || "" == mime_types){
        mime_types = [{title : "Image files", extensions : "mp3,mp4,flv,doc,docx,ppt,pptx,pdf,xls,xlsx,swf"}];
    }
    if(undefined == file_size || "" == file_size){
        file_size = '300mb';
    }
    // html4是不支持多文件上传的
    $("#" + id).plupload({
        runtimes: 'html5,flash',
        url: upload_url,
        unique_names : true,
        multi_selection : true,
        multipart: true,
        max_file_size: file_size,
        chunk_size: file_size,
        filters: mime_types,
        prevent_duplicates: true,
        rename: false,
        sortable: true,
        dragdrop: true,
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },
        flash_swf_url: '<%=resourcePath%>static/global/js/plupload1/plupload/js/Moxie.swf',
        silverlight_xap_url: '<%=resourcePath%>static/global/js/plupload1/plupload/js/Moxie.xap',
        init: {
            FileUploaded: function (up, file, result) {

                // 回调函数
                backUploadCallBack(id,result.response,file.name);
                // 保存按钮设置（去除正在上传提示,变成保存按钮）
                btn_setting();
            },
            BeforeUpload: function (uploader,file) {
               // 上传文件的提示语
                uploadPrompt();
               // 更改每个文件上传的url
                fileUpload(uploader,file);

            }

        }


    });
}

// 上传成功后回调
function backUploadCallBack(id, response_, fileName) {
    var data = eval("(" + response_ + ")");
    var status = data['status'];
    var upload = "";
    if(200 == status){
        var result = data['result'];
        var fileId = result.fid;
        upload = fileId + "," + fileName;
    }
    var value = $("#fileList").val();
    value += value == '' ? upload : ";" + upload;
    $("#fileList").val(value)

    file_id_path[fileId] = result;
}


var fileToken = [];
// 上传文件初始化
function storageInit(uploader,file) {
    // 上传文件隐藏保存按钮
    parent.$(".layui-layer-iframe").find(".layui-layer-btn .layui-layer-btn0").css("display","none");
    var fileName = file.name;
    var timeStamp = Date.parse(new Date()) / 1000 + 180;
    var sign = md5(fastUserkey + timeStamp);
    var suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    var crypto = 0;
    if(suffix == 'flv' || suffix == 'mp4' || suffix == 'mp3' || suffix == 'MP3'){
        crypto = 1;
    }
    var url_init = storageId + "/api/v1/file/init?userKey=" + fastUser + "&timeStamp=" + timeStamp + "&sign=" + sign + "&fileName=" + fileName + "&fileType=" + suffix + "&crypto=" + crypto;
    $.ajax({
        url: url_init,
        type: "get",
        dataType: "json",
        success: function (data) {
            var status = data.status;
            var url_upload = "";
            if (200 == status) {
                var result = data.result;
                var token = result.token;
                var object = new Object();
                object.fid = file.id;
                object.token = token;
                fileToken.push(object)
            }

        }
    });
};

// 删除文件即要删除对应的token
function removeFile(uploader,file) {
    var fileId = file.id;
    fileToken.forEach(function (value,i) {
        if(value.fid == fileId){
            fileToken.splice(i,1 );
            return false;
        }
    });
}

// 上传之前更改每个文件的路径
function fileUpload(uploader,file) {
    var fileId = file.id;
    var timeStamp = Date.parse(new Date()) / 1000 + 180;
    var token = "";
    var url_upload = "";
    fileToken.forEach(function (value,index) {
        if(value.fid == fileId){
            token =  value.token;
            fileToken.splice(index,1);
            return false;
        }
    });
    url_upload = storageId + "/api/v1/file/upload?timeStamp=" + timeStamp + "&fileSize=&offset=0&token="+ token;
    uploader.settings.url = url_upload;
}


// 保存按钮设置（去除正在上传提示,变成保存按钮）
function btn_setting() {
    if(fileToken.length == 0){
        parent.$(".layui-layer-iframe").find(".layui-layer-btn .btn").remove();
        parent.$(".layui-layer-iframe").find(".layui-layer-btn .layui-layer-btn0").css("display","");
    }
}

// 上传文件的提示语
function uploadPrompt() {
    if(parent.$(".layui-layer-iframe").find(".layui-layer-btn .btn").length == 0){
        var inner = '<a class="btn" style="background-color: #4f9fe4;color: #fff;height: 30px;">正在上传......</a>';
        parent.$(".layui-layer-iframe").find(".layui-layer-btn").prepend(inner);
    }
}